<template>
  <div class="template-edit">
    <div class="header">
      <h2>编辑模板</h2>
      <el-button-group>
        <el-button @click="back">返回</el-button>
        <el-button type="primary" :loading="saving" @click="save">
          保存
        </el-button>
      </el-button-group>
    </div>

    <div v-loading="loading" class="edit-content">
      <el-form
        v-if="formData"
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="edit-form"
      >
        <!-- 基本信息 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>

          <el-form-item label="模板名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入模板名称" />
          </el-form-item>

          <el-form-item label="显示标题" prop="title">
            <el-input v-model="formData.title" placeholder="请输入显示标题" />
          </el-form-item>

          <el-form-item label="模板描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              placeholder="请输入模板描述"
            />
          </el-form-item>

          <el-form-item label="封面图" prop="cover">
            <upload-field v-model="formData.cover" accept="image/*" />
          </el-form-item>

          <el-form-item label="详情图" prop="detailImage">
            <upload-field v-model="formData.detailImage" accept="image/*" />
          </el-form-item>

          <el-form-item label="标签" prop="tags">
            <el-select
              v-model="formData.tags"
              multiple
              filterable
              allow-create
              placeholder="请选择或输入标签"
            >
              <el-option
                v-for="tag in tagOptions"
                :key="tag"
                :label="tag"
                :value="tag"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="是否公开" prop="isPublic">
            <el-switch v-model="formData.isPublic" />
          </el-form-item>
        </el-card>

        <!-- 模板配置 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>模板配置</span>
            </div>
          </template>

          <workflow-template-manager
            v-model="template"
            @change="handleTemplateChange"
          />
        </el-card>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { TemplateService } from '@/services/template'
import WorkflowTemplateManager from '@/components/WorkflowTemplateManager.vue'
import UploadField from '@/components/UploadField.vue'
import type { WorkflowTemplate } from '@/types/workflow'

const router = useRouter()
const route = useRoute()
const formRef = ref<FormInstance>()
const loading = ref(false)
const saving = ref(false)

// 表单数据
const formData = ref({
  name: '',
  title: '',
  description: '',
  type: 'image',
  cover: '',
  detailImage: '',
  samples: [] as string[],
  tags: [] as string[],
  isPublic: false,
  serverIds: [] as string[],
  excludeServerIds: [] as string[],
  powerConsumption: 0,
  sort: 0
})

// 模板配置
const template = ref<WorkflowTemplate>({
  version: '1.0.0',
  workflow: {},
  params: [],
  layout: {
    groups: []
  }
})

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入显示标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  cover: [
    { required: true, message: '请上传封面图', trigger: 'change' }
  ]
}

// 标签选项
const tagOptions = [
  '图像生成',
  '图像编辑',
  '风格迁移',
  '人像处理',
  '场景重建'
]

// 获取模板数据
const getTemplate = async () => {
  try {
    loading.value = true
    const id = route.params.id as string
    const data = await TemplateService.getTemplate(id)

    // 更新表单数据
    Object.assign(formData.value, {
      name: data.name,
      title: data.title,
      description: data.description,
      type: data.type,
      cover: data.cover,
      detailImage: data.detailImage,
      samples: data.samples,
      tags: data.tags,
      isPublic: data.isPublic,
      serverIds: data.serverIds,
      excludeServerIds: data.excludeServerIds,
      powerConsumption: data.powerConsumption,
      sort: data.sort
    })

    // 更新模板配置
    template.value = JSON.parse(data.template)
  } catch (error) {
    console.error('Failed to get template:', error)
    ElMessage.error('获取模板失败')
    router.back()
  } finally {
    loading.value = false
  }
}

// 保存模板
const save = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    saving.value = true

    const id = route.params.id as string
    const templateData = {
      ...formData.value,
      workflow: JSON.stringify(template.value.workflow),
      template: JSON.stringify(template.value)
    }

    await TemplateService.updateTemplate(id, templateData)
    ElMessage.success('保存成功')
    router.push('/template')
  } catch (error: any) {
    console.error('Failed to save template:', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    saving.value = false
  }
}

// 返回列表
const back = () => {
  router.back()
}

// 模板变更处理
const handleTemplateChange = () => {
  // 可以在这里处理模板变更后的逻辑
}

// 初始化
onMounted(() => {
  getTemplate()
})
</script>

<style scoped lang="scss">
.template-edit {
  padding: 24px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    h2 {
      margin: 0;
    }
  }

  .edit-content {
    min-height: 200px;
  }

  .edit-form {
    max-width: 1200px;
    margin: 0 auto;

    .form-card {
      margin-bottom: 24px;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }
  }
}
</style> 